<template>
  <Form class="xtx-form" :validation-schema="mySchema" autocomplete="off" v-slot='{errors}' ref="formCom" >
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field :class="{err:errors.account}" class="input" type="text" placeholder="请输入用户名" name="account" v-model="form.account" />
      </div>
      <div class="error" v-if="errors.account">{{errors.account}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{err:errors.mobile}" class="input" type="text" placeholder="请输入手机号" name="mobile" v-model="form.mobile" />
      </div>
      <div class="error" v-if="errors.mobile">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{err:errors.code}" class="input" type="text" placeholder="请输入验证码" name="code" v-model="form.code" />
        <span class="code" @click="send">{{time===0?'发送验证码':`${time}秒重新发送`}}</span>
      </div>
      <div class="error" v-if="errors.code">{{errors.code}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{err:errors.password}" class="input" type="password" placeholder="请输入密码" name="password" v-model="form.password" />
      </div>
      <div class="error" v-if="errors.password">{{errors.password}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{err:errors.rePassword}" class="input" type="password" placeholder="请确认密码" name="rePassword" v-model="form.rePassword" />
      </div>
      <div class="error" v-if="errors.rePassword">{{errors.rePassword}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即提交</a>
  </Form>
</template>

<script>
import schema from '@/utils/vee-validate-schema'
import Message from '@/components/library/Message'
import { ref, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { useIntervalFn } from '@vueuse/shared'
import { Form, Field } from 'vee-validate'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user'
export default {
  name: 'CallbackPatch',
  components: { Form, Field },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    const store = useStore()
    const router = useRouter()
    const formCom = ref(null)
    const form = ref({
      account: null,
      mobile: null,
      code: null,
      password: null,
      rePassword: null
    })
    const mySchema = {
      account: schema.accountApi,
      mobile: schema.mobile,
      code: schema.code,
      password: schema.password,
      rePassword: schema.rePassword
    }

    // 设置计时器 停止 开始
    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0)pause()
    }, 1000, false) // 是否立即开启
    onUnmounted(() => {
      pause()
    })
    // 发送验证码
    async function send () {
      const valid = mySchema.mobile(form.value.mobile) // 校验手机号
      if (valid === true) {
        if (time.value !== 0) return
        try {
          await userQQPatchCode(form.value.mobile)
          Message({ type: 'success', text: '发送成功' })
          time.value = 60
          resume() // 开启定时
        } catch (e) {
          Message({ type: 'error', text: e.response.data.message || '发送失败' })
        }
      } else {
        formCom.value.setFieldError('mobile', valid) // 显示错误信息
      }
    }
    // 立即提交
    async function submit () {
      // 表单校验 valid===true通过
      const valid = await formCom.value.validate()
      if (valid) {
        try {
          const data = await userQQPatchLogin({
            unionId: props.unionId,
            ...form.value
          })
          // 存储用户信息
          const { id, account, avatar, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })
          // 合并购物车
          store.dispatch('cart/mergeCart').then(() => {
            // 读取记录的原地址信息，以在完成登录后回到原先页面
            router.push(store.state.user.redirectUrl)
            Message({ type: 'success', text: '信息已完善' })
          })
        } catch (e) {
          if (e.response.data)Message({ type: 'error', text: e.response.data.message || '信息完善失败' })
        }
      }
    }
    return { formCom, form, mySchema, send, time, submit }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
